package com.yuerlive.paperplane.data.source.remote;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.yuerlive.paperplane.data.ZhihuDailyNews;
import com.yuerlive.paperplane.data.ZhihuDailyNewsQuestion;
import com.yuerlive.paperplane.data.source.datasource.ZhihuDailyNewsDataSource;
import com.yuerlive.paperplane.retrofit.RetrofitService;
import com.yuerlive.paperplane.utils.DateFormatUtil;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Admin on 2017/10/12.
 */

public class ZhihuDailyNewsRemoteDataSoure implements ZhihuDailyNewsDataSource{
    @Nullable
    private static ZhihuDailyNewsRemoteDataSoure instance=null;
    //prevent direct instantiation
    private ZhihuDailyNewsRemoteDataSoure(){}
    public static ZhihuDailyNewsRemoteDataSoure getInstance(){
        if(instance==null){
            instance=new ZhihuDailyNewsRemoteDataSoure();
        }
        return  instance;
    }
    @Override
    public void getZhihuDailyNews(boolean forceUpdate, boolean clearCache, long date, @NonNull loadZhihuDailyNewsCallback callback) {
        Retrofit retrofit =new Retrofit.Builder().baseUrl(RetrofitService.ZHIHU_DAILY_BASE)
                .addConverterFactory(GsonConverterFactory.create()).build();
        RetrofitService.ZhihuDailyService service=retrofit.create(RetrofitService.ZhihuDailyService.class);
        service.getZhihuList(DateFormatUtil.formatZhihuDailyDateLongToString(date))
                .enqueue(new Callback<ZhihuDailyNews>() {
                    @Override
                    public void onResponse(Call<ZhihuDailyNews> call, Response<ZhihuDailyNews> response) {
                        long timestamp =DateFormatUtil.formatZhihuDailyDateStringToLong(response.body().getDate());
                        Log.d("TAG", "onResponse: timestamp " + timestamp);
                        for(ZhihuDailyNewsQuestion item:response.body().getStories()){
                            item.setTimestamp(timestamp);
                        }
                        callback.onNewsLoad(response.body().getStories());
                    }

                    @Override
                    public void onFailure(Call<ZhihuDailyNews> call, Throwable t) {
                      callback.onDataNotAvailable();
                    }
                });

    }

    @Override
    public void getFavorites(@NonNull loadZhihuDailyNewsCallback callback) {

    }

    @Override
    public void getItem(int itemId, @NonNull GetNewsItemCallback callback) {

    }

    @Override
    public void favoriteItem(int itemId, boolean favorite) {

    }

    @Override
    public void saveAll(@NonNull List<ZhihuDailyNewsQuestion> list) {

    }
}
